#include "testfunctions.h"

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>

#include <iostream>
#include <QtDebug>

namespace boost_test {

void TestSignal() {}

void TestIOService()
{
  boost::asio::io_service io_service;
  boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(2));
  // boost::chrono::microseconds start;
  boost::chrono::steady_clock::time_point start = boost::chrono::high_resolution_clock::now();
  timer1.async_wait([&](const boost::system::error_code &code) -> void {
    decltype(start) end1 = boost::chrono::high_resolution_clock::now();
    auto elapsed = end1 - start;
    printInfo("Waiting seconds: %d", elapsed.count() / std::nano().den);
  });
  io_service.run();
}

void InternalRead(
                boost::array<char, 4096> buffer,
                boost::asio::ip::tcp::socket* sock,
                const boost::system::error_code &ec,
                std::size_t bytes_transferred) {
  if (!ec) {
    sock->async_read_some(boost::asio::buffer(buffer),
                           boost::bind(&InternalRead, buffer, sock, _1, _2));
    qDebug() << QString::fromUtf8(QByteArray(buffer.data(), bytes_transferred));
  } else {
    printf("error happens: \n");
  }
}

void TestHttpClient()
{
  static constexpr int BUFFER_SIZE = 4096;
  boost::asio::io_service io_service;
  boost::asio::ip::tcp::resolver resolver(io_service);
  boost::asio::ip::tcp::socket sock(io_service);
  boost::array<char, 4096> buffer;

  auto connect_handler = [&](const boost::system::error_code &ec) {
    if (!ec) {
      boost::asio::write(sock, boost::asio::buffer("GET / HTTP 1.1\r\nHost: highscore.de\r\n\r\n"));
      sock.async_read_some(boost::asio::buffer(buffer), boost::bind(&InternalRead, buffer, &sock, _1, _2));
    }
  };

  auto resolve_handler = [&](const boost::system::error_code &ec,
                             boost::asio::ip::tcp::resolver::iterator it) {
    if (!ec) {
      sock.async_connect(*it, connect_handler);
    }
  };

  boost::asio::ip::tcp::resolver::query query("www.highscore.de", "80");
  resolver.async_resolve(query,resolve_handler);
  io_service.run();
}

} // namespace boost_test
